<template>
    <div class="iframe-container">
        <iframe id="aliyunPreview" ref="aliyunPreview" :src="defaultUrl" allow="fullscreen" allowfullscreen="true"
            scrolling="no" frameborder='0' :style="{ width: '100%', minHeight: '700px' }">
        </iframe>
        <!-- <el-button class="fullScreen-btn" size="default" :icon="FullScreen" @click="requestFullScreen"></el-button> -->
        <div v-if="isPdf" class="fullScreen-btn cursor-pointer" @click="requestFullScreen">
            <el-icon>
                <FullScreen />
            </el-icon>
        </div>
    </div>
</template>
<script setup lang='ts'>
import {
    FullScreen
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncInquireusertotpdataid9, asyncOssUpload8 } from '../../../api';
import { Storekey } from "../../../interface";
import Alymodel from '../../../mysql_interface/model';

const defaultUrl = "https://preview.imm.aliyun.com/index.html"

type P = {
    num: number | undefined;
    lessionid: number | undefined;
    question: Alymodel.Ivideoquestion[];
    course: Alymodel.IMcourse;
};
const p = defineProps<P>()

const store = useStore(Storekey)
const route = useRoute()
const router = useRouter()
// 当前登录用户
const user = computed(() => {
    return store.state.user;
});
const teamId = computed(() => {
    return Number(user.value?.teamid);
});

watch(() => p.course, (e) => {
    x.value = true
    Refresh()
})
watch(() => p.lessionid, (e) => {
    x.value = true
    Refresh()
})

// 销毁
onBeforeUnmount(() => {
    window.removeEventListener("message", message);
})
onMounted(() => {
    start()
})

const x = ref(true)
const isPdf = ref(true)
const aliyunPreview = ref<HTMLIFrameElement>()
async function start() {
    window.addEventListener("message", message, false);
}

function message(e: MessageEvent<any>) {
    let res;
    if (e.data && typeof e.data === "string") {
        res = JSON.parse(e.data);
        switch (res.action) {
            case "preview.ready":
                init(p.course.ID);
                break;
            case "logic.refreshToken":
                setToken();
                break;
            case "message.error":
                break;
        }
    }
}

async function init(cid: number | undefined) {
    try {
        if (!x.value) return;
        x.value = false;
        const userid = user.value?.ID;
        const arr = await asyncInquireusertotpdataid9({
            course_ID: cid,
            // num: p.num,
            lessionid: p.lessionid,
        });
        const url = arr.TgtUri;
        const fileType = urlDemo(url, 2) || ''
        isPdf.value = fileType.includes('pdf')
        if (arr) {
            const { accessKeyId, accessKeySecret, securityToken, } = await asyncOssUpload8();
            sendMessage("preview.init", {
                url,
                region: "oss-cn-beijing",
                bucket: "hterobot-pdf",
                accessKeyId,
                accessKeySecret,
                stsToken: securityToken,
                wmType: 1,
                wmValue: String(userid),
                wmColor: "rgba(192, 192, 192, 0.2)",
                copy: 1
            });
        } else {
            ElMessage.error("没有权限哦！")
        }
    } catch (error) {
        console.error("init catch err=>", error)
    }
}

async function setToken() {
    const data = await asyncOssUpload8();
    console.log("setToken=>", data)
    sendMessage("logic.setToken", {
        region: "oss-cn-beijing",
        accessKeyId: data.accessKeyId,
        accessKeySecret: data.accessKeySecret,
        stsToken: data.securityToken,
        bucket: "hterobot-pdf",
    });
}

function sendMessage(action: string, data: any) {
    if (aliyunPreview.value) {
        aliyunPreview.value.contentWindow?.postMessage(json2str({ action: action, data: data, }), "*")

    }
}

function json2str(obj: { action: string, data: any }) {
    return JSON.stringify(obj, function (key, val) {
        if (typeof val === "function") {
            val = val.toString();
        }
        return val;
    });
}

function Refresh() {
    if (aliyunPreview.value && aliyunPreview.value.contentWindow) {
        aliyunPreview.value.contentWindow.location.href = `${defaultUrl}?_q=${Math.random()}`
    }
}

function requestFullScreen() {
    let requestMethod = aliyunPreview.value?.requestFullscreen
    if (requestMethod) {
        requestMethod.call(aliyunPreview.value)
    }
}

// 获取url中需要的数据  type  1: 获取文件名  2：获取后缀  3：获取文件名+后缀  4:获取文件前缀
function urlDemo(url: string, type: number) {
    let filename = url.substring(url.lastIndexOf('/') + 1)
    switch (type) {
        case 1: return filename;
        case 2: return filename.substring(filename.lastIndexOf(".") + 1);
        case 3: return filename.substring(0, filename.lastIndexOf("."));
        case 4: return url.substring(0, url.lastIndexOf('/') + 1)
    }
}

</script>

<style scoped>
.iframe-container {
    position: relative;
}

.fullScreen-btn {
    font-size: 40px;
    line-height: 40px;
    position: absolute;
    /* top: 20px;
    right: 20px; */
    bottom: 20px;
    left: 20px;
    opacity: 0.3;
}
</style>